//
//  ReadyPayVC.m
//  zhiche--delivery
//
//  Created by LeeBruce on 16/10/9.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "ReadyPayVC.h"
#import "RootViewController.h"
#import "TopBackView.h"
#import "Common.h"
#import "MineOrderModel.h"
#import "ForntCell.h"//付款
#import "RLNetworkHelper.h"//网络判断
#import "WKProgressHUD.h"//提示框
#import <MJRefresh.h>//下拉刷新
#import "NullView.h"
#import "ReadyPayDetailVC.h"

//待付款
#define order_pendpaying @"pendpaying"
#define defaultShow 10


@interface ReadyPayVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic) int pageNo;
@property (nonatomic) NSInteger pageTotal;
@property (nonatomic) int pageSize;

@property (nonatomic,strong) UIView *netView;
@property (nonatomic,strong) WKProgressHUD *hud;
@property (nonatomic,strong) NullView *nullView;
@property (nonatomic,strong) NSMutableArray *dataArray;

@end

@implementation ReadyPayVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = GrayColor;
    self.pageNo = 1;
    self.pageSize = defaultShow;
    
    self.nullView = [[NullView  alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight  - 45 * kHeight) andTitle:@""];
    self.nullView.backgroundColor = GrayColor;
    
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    self.dataArray = [NSMutableArray array];

    Common *c = [[Common alloc]init];
    //创建无网络状态view
    self.netView = [c noInternet:@"网络连接失败，请检查网络设备" and:self action:@selector(NoNetPressBtn) andCGreck:CGRectMake(0, 0, Main_Width, Main_height-64)];

    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"待付款"];
   
    
    topBackView.rightButton.hidden = YES;
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:topBackView];


    [self initSubViews];
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    [self addSwipeRecognizer];
    
    
}
#pragma mark - UIGestureRecognizerDelegate

- (void)addSwipeRecognizer
{
    // 初始化手势并添加执行方法
    UISwipeGestureRecognizer *swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(return)];
    
    // 手势方向
    swipeRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
    
    // 响应的手指数
    swipeRecognizer.numberOfTouchesRequired = 1;
    
    // 添加手势
    [[self view] addGestureRecognizer:swipeRecognizer];
}

#pragma mark 返回上一级
- (void)return
{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

-(void)initSubViews
{
    
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64 , screenWidth, screenHeight - 64  ) style:UITableViewStyleGrouped];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = GrayColor;
    [self.view addSubview:self.tableView];
    
    //mj
    [self.tableView.mj_header beginRefreshing];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];
    
    //无网络状态
    [self createNetWorkAndStatue];

}

-(void)createNetWorkAndStatue{
    
    //判断是否有网
    [self judgeNetWork];
    //创建加载状态
}

//判断是否有网
-(void)judgeNetWork{
    if (![RLNetworkHelper isConnectedToNetwork]) {
        [self.tableView addSubview:self.netView];
        self.hud = [WKProgressHUD showInView:self.view withText:@"" animated:YES];
        
    }
    else{
        [self.netView removeFromSuperview];
        [self initDataSource];
    }
}

//无网络状态
-(void)NoNetPressBtn{
    if ([RLNetworkHelper isConnectedToNetwork]) {
        [self.netView removeFromSuperview];
        [self initDataSource];
    } else {
        [self.hud dismiss:YES];
    }
}

-(void)downRefresh{
    
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    self.pageNo = 1;
    
    [self judgeNetWork];
}
-(void)upRefresh{
    
    if (self.pageNo != (int)self.pageTotal) {
        self.pageNo ++;
        [self judgeNetWork];
        [self.tableView.mj_footer endRefreshing];
    }else{
        self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
    }
    [self.tableView.mj_header endRefreshing];
}


-(void)initDataSource
{
    
    self.nullView.label.text = @"暂无执行中订单";
   
    //订单状态接口
    NSString *urlString = [NSString stringWithFormat:@"%@order/%@?pageNo=%d&pageSize=%d",Main_interface,order_pendpaying,self.pageNo,self.pageSize];
    
    [Common requestWithUrlString:urlString contentType:application_json finished:^(id responseObj) {
        
        [self.hud dismiss:YES];
        
        self.pageTotal = [responseObj[@"data"][@"page"][@"totalPage"] integerValue];
        
        if (self.pageNo == 1 ) {
            [self.dataArray removeAllObjects];
        }
        
        if ([responseObj[@"success"] boolValue]) {
            
            [self.hud dismiss:YES];
            
            NSArray *array = responseObj[@"data"][@"orders"];
            
            for (id obj in array) {
                MineOrderModel *model = [[MineOrderModel alloc]init];
                
                [model setValuesForKeysWithDictionary:obj];
                
                [self.dataArray addObject:model];
            }
            
            
            if (self.dataArray.count >0) {
                
                [self.nullView removeFromSuperview];
                
            } else {
                
                [self.tableView addSubview:self.nullView];
                
            }
            
            [self.tableView reloadData];
            
        }
        
        
    } failed:^(NSString *errorMsg) {
        
        
        
        [self.hud dismiss:YES];
        
        NSLog(@"%@",errorMsg);
        
    }];
    
    
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //    return 3;
    
    return self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
            NSString *string = @"fontCell";
            ForntCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
            if (!cell) {
                cell = [[ForntCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:string];
            }
    
            if (self.dataArray.count > 0) {
                cell.model = self.dataArray[indexPath.section];
    
    
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
            [cell.payButton addTarget: self action:@selector(payButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            cell.payButton.tag = indexPath.section + 200;
    
    [cell.cancelButton addTarget: self action:@selector(cancelButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    cell.cancelButton.tag = indexPath.section + 400;

    
            return cell;
            
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
            ReadyPayDetailVC *readyVC = [[ReadyPayDetailVC alloc]init];
    
             MineOrderModel *model = self.dataArray[indexPath.section];
    
            readyVC.orderId = model.ID;
    
            [self.navigationController pushViewController:readyVC animated:YES];
        }

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 188 * kHeight;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

#pragma mark 准备支付
-(void)payButtonAction:(UIButton *)sender
{
    
    MineOrderModel *model = [[MineOrderModel alloc]init];
    model = self.dataArray[sender.tag - 200];
    ReadyPayDetailVC *reayVC = [[ReadyPayDetailVC alloc]init];
    reayVC.orderId = model.ID;
    
    [self.navigationController pushViewController:reayVC animated:YES];
}

//#pragma mark 取消订单
-(void)cancelButtonAction:(UIButton *)sender
{

    MineOrderModel *model = [[MineOrderModel alloc]init];
    model = self.dataArray[sender.tag - 400];

    UIAlertController * alert =[UIAlertController alertControllerWithTitle:@"提示" message:@"确定是否取消订单" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action =[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
        NSMutableDictionary * dicUrl = [[NSMutableDictionary alloc]init];
        [dicUrl setObject:model.ID forKey:@"orderid"];
        [dicUrl setObject:@"" forKey:@"reason"];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            [Common afPostRequestWithUrlString:Mine_Order_Cancel parms:dicUrl finishedBlock:^(id responseObj) {
                
                NSMutableDictionary * dicObj =[NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableContainers error:nil];
                NSString * string = [NSString stringWithFormat:@"%@",dicObj[@"success"]];
                if ([string isEqualToString:@"1"]) {
                    
                    [WKProgressHUD popMessage:dicObj[@"message"] inView:self.view duration:1.5 animated:YES];

                    //延迟执行
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                        self.pageNo = 1;
                        
                        [self initDataSource];

                    });
                    
                }
                
            } failedBlock:^(NSString *errorMsg) {
            }];
            
        });
    }];
    UIAlertAction * action1 =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:action1];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];

}

-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES];
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    [rootVC setTabBarHidden:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
